<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="招聘分类名称" prop="cateName">
        <el-input
          v-model="queryParams.cateName"
          placeholder="请输入招聘分类名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="招聘分类状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:cate:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="cateList"
      row-key="cateId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="cateName" label="招聘分类名称" width="260"></el-table-column>
      <el-table-column prop="sort" label="排序" width="200"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:cate:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:cate:add']"
          >新增</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:cate:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改招聘分类对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="70%" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级分类" prop="parentId">
              <treeselect v-model="form.parentId" :options="cateOptions" :normalizer="normalizer" placeholder="选择上级招聘分类" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="招聘名称" prop="cateName">
              <el-input v-model="form.cateName" placeholder="请输入招聘分类名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="分类icon">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleUploadCateImageSuccess"
                :before-upload="handleCateImageBeforeUpload"
                :limit="limit"
                :on-error="handleCateImageUploadError"
                :on-exceed="handleCateImageExceed"
                ref="imageUpload"
                :on-remove="handleCateImageUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="imageList"
                :on-preview="handleCateImagePictureCardPreview"
                :class="{hide: this.imageList.length >= this.limit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题">
              <el-input v-model="form.title" placeholder="请输入标题" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副标题">
              <el-input v-model="form.subTitle" placeholder="请输入副标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="简介">
              <el-input v-model="form.intro" placeholder="请输入简介" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="副简介">
              <el-input v-model="form.subIntro" placeholder="请输入副简介" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="联系方式">
              <el-input v-model="form.contact" placeholder="请输入联系方式标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详情1">
              <el-input v-model="form.subContact1" placeholder="请输入详情1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详情2">
              <el-input v-model="form.subContact2" placeholder="请输入详情2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="工作地址">
              <el-input v-model="form.address" placeholder="请输入工作地址标题" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详情1">
              <el-input v-model="form.subAddress1" placeholder="请输入详情1" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="详情2">
              <el-input v-model="form.subAddress2" placeholder="请输入详情2" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="分类状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{dict.label}}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="二维码上传">
              <el-upload
                multiple
                :action="uploadImgUrl"
                list-type="picture-card"
                :on-success="handleIconListUploadSuccess"
                :before-upload="handleIconListBeforeUpload"
                :limit="eqLimit"
                :on-error="handleIconListUploadError"
                :on-exceed="handleIconListExceed"
                ref="imageUpload"
                :on-remove="handleIconListUploadDelete"
                :show-file-list="true"
                :headers="headers"
                :file-list="iconList"
                :on-preview="handlePictureCardPreview"
                :class="{hide: this.iconList.length >= this.eqLimit}"
              >
                <i class="el-icon-plus"></i>
              </el-upload>
              <!-- 上传提示 -->
              <div class="el-upload__tip" slot="tip" v-if="showTip">
                请上传
                <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
                <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
                的文件
              </div>
              <el-dialog
                :visible.sync="dialogVisible"
                title="预览"
                width="800"
                append-to-body
              >
                <img
                  :src="dialogImageUrl"
                  style="display: block; max-width: 100%; margin: 0 auto"
                />
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCate, getCate, delCate, addCate, updateCate, listCateExcludeChild } from "@/api/system/cate"

import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import {getSite, getToken} from "@/utils/auth";
import {listToString, splitImages} from "@/api/tool/upload";

export default {
  name: "reCate",
  dicts: ['sys_normal_disable'],
  components: { Treeselect },
  props: {
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    eqLimit: {
      type: Number,
      default: 2,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 表格树数据
      cateList: [],
      // 招聘分类树选项
      cateOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 查询参数
      queryParams: {
        tenantId: getSite(),
        typeId: 6,
        cateName: undefined,
        status: undefined
      },
      // 查询参数
      editQueryParams: {
        tenantId: getSite(),
        typeId: 6
      },
      // 表单参数
      form: {},
      // 上传的图片服务器地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传图片个数
      number: 0,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      fileList: [],   //招聘分类icon
      imageList: [],  //招聘分类图片
      iconList: [],   //招聘分类列表icon
      indexImageList: [], //招聘分类首页图片
      indexIconList: [],  //招聘分类首页icon
      uploadList: [], //临时上传列表
      dialogVisible: false,
      dialogImageUrl: "",
    }
  },
  created() {
    this.getList()
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    /** 查询招聘分类列表 */
    getList() {
      this.loading = true;
      listCate(this.queryParams).then(response => {
        this.cateList = this.handleTree(response.data, "cateId")
        this.loading = false
      })
    },
    /** 转换招聘分类数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.cateId,
        label: node.cateName,
        children: node.children
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        cateId: undefined,
        parentId: undefined,
        cateName: undefined,
        sort: undefined,
        cateIntro: undefined,
        cateIcon: undefined,
        cateImage: undefined,
        status: "0"
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset()
      if (row != undefined) {
        this.form.parentId = row.cateId
      }
      this.open = true
      this.title = "添加招聘分类"
      this.fileList = [];
      this.imageList = [];
      this.iconList = [];
      this.indexImageList = [];
      this.indexIconList = [];
      this.formData = {};
      listCate(this.editQueryParams).then(response => {
        this.cateOptions = this.handleTree(response.data, "cateId")
      })
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false
      this.isExpandAll = !this.isExpandAll
      this.$nextTick(() => {
        this.refreshTable = true
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getCate(row.cateId).then(response => {
        this.iconList = [];
        let formData = response.data
        if(formData.cateIntro){
          let cateIntro = JSON.parse(formData.cateIntro);
          formData.title = cateIntro.title;
          formData.subTitle = cateIntro.subTitle;
          formData.intro = cateIntro.intro;
          formData.subIntro = cateIntro.subIntro;
          formData.contact = cateIntro.contact;
          formData.subContact1 = cateIntro.subContact1;
          formData.subContact2 = cateIntro.subContact2;
          formData.address = cateIntro.address;
          formData.subAddress1 = cateIntro.subAddress1;
          formData.subAddress2 = cateIntro.subAddress2;
          if(cateIntro.eqImage){
            var imageArr = cateIntro.eqImage.split(';');
            for (var i = 0; i < imageArr.length; i++) {
              this.iconList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
            }
          }
        }
        this.form = formData
        this.open = true
        this.title = "修改招聘分类"

        //招聘分类图片
        this.imageList = [];
        if(this.form.cateImage){
          var imageArr = this.form.cateImage.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.imageList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }


        this.editQueryParams.cateId = row.cateId;
        listCateExcludeChild(this.editQueryParams).then(response => {
          this.cateOptions = this.handleTree(response.data, "cateId")
          if (this.cateOptions.length == 0) {
            const noResultsOptions = { cateId: this.form.parentId, cateName: this.form.parentName, children: [] }
            this.cateOptions.push(noResultsOptions)
          }
        })
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 租户ID
          this.form.tenantId = getSite();
          this.form.typeId = this.queryParams.typeId;
          // 招聘分类图片
          this.form.cateImage = splitImages(this.imageList);
          const intro = {title: this.form.title, subTitle: this.form.subTitle, intro: this.form.intro, subIntro: this.form.subIntro,
            contact: this.form.contact, subContact1 : this.form.subContact1, subContact2 : this.form.subContact2, address : this.form.address,
            subAddress1: this.form.subAddress1, subAddress2 : this.form.subAddress2,eqImage: splitImages(this.iconList) }
          this.form.cateIntro = JSON.stringify(intro);
          if (this.form.cateId != undefined) {
            updateCate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addCate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.cateName + '"的数据项？').then(function() {
        return delCate(row.cateId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    // 上传前loading加载
    handleBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedSuccessfully();
      }
    },
    // 上传结束处理
    uploadedSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.fileList = this.fileList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.fileList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleUploadDelete(file) {
      const findex = this.fileList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.fileList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.fileList));
      }
    },
    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //招聘分类图片方法
    // 上传前loading加载
    handleCateImageBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadCateImageSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedCateImageSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedCateImageSuccessfully();
      }
    },
    // 上传结束处理
    uploadedCateImageSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.imageList = this.imageList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.imageList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleCateImageExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleCateImageUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleCateImageUploadDelete(file) {
      const findex = this.imageList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.imageList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.imageList));
      }
    },
    // 预览
    handleCateImagePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    // 列表icon图片相关
    // 上传前loading加载
    handleIconListBeforeUpload(file) {
      let isImg = false;
      if (this.iconList.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleIconListUploadSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedIconListSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedIconListSuccessfully();
      }
    },
    // 上传结束处理
    uploadedIconListSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.iconList = this.iconList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.iconList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleIconListExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.eqLimit} 个!`);
    },
    // 上传失败
    handleIconListUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleIconListUploadDelete(file) {
      const findex = this.iconList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.iconList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.iconList));
      }
    },
  }
}
</script>
